package org.jeecg.modules.xl.mpapi.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.annotation.Export2Swagger;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.shiro.IgnoreAuth;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.xl.as.entity.XlCustomerAs;
import org.jeecg.modules.xl.as.service.IXlCustomerAsService;
import org.jeecg.modules.xl.brand.entity.XlProductBrand;
import org.jeecg.modules.xl.brand.service.IXlProductBrandService;
import org.jeecg.modules.xl.h5api.vo.MyStoreVO;
import org.jeecg.modules.xl.mpapi.vo.*;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.jeecg.modules.xl.product.entity.XlProductInfo;
import org.jeecg.modules.xl.product.service.IXlProductCustomerPriceService;
import org.jeecg.modules.xl.producttype.service.IXlProductTypeService;
import org.jeecg.modules.xl.store.entity.XlCustomerMystore;
import org.jeecg.modules.xl.store.service.IXlCustomerMystoreService;
import org.jeecg.modules.xl.store.service.IXlCustomerStoreInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author deco
 * @create 2025-02-24
 */
@Api(tags="小程序-首页接口")
@RestController
@RequestMapping("/htmmp/main")
@Export2Swagger
@Slf4j
public class MPMainConller {

    @Autowired
    private IXlProductCustomerPriceService productInfoService;
    @Autowired
    private IXlProductBrandService productBrandService;
    @Autowired
    private IXlProductTypeService productTypeService;
    @Value("${pichost}")
    private String baseUrl;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IXlCustomerMystoreService mystoreService;
    @Autowired
    private ISysUserService sysUserService;

    //获取banner位
    @ApiOperation(value = "获取banner广告位", notes = "获取banner广告位")
    @GetMapping(value = "/getBannerList")
    @Export2Swagger
    public Result<List<BannerVo>> getBannerList() {
        BannerVo banner1 = new BannerVo("http://s3.bugless.site:7015/slt/banner/banner1.png", "#", "xx");
        BannerVo banner2 = new BannerVo("http://s3.bugless.site:7015/slt/banner/banner2.png", "#", "xx");
        return Result.OK(Arrays.asList(banner1, banner2));
    }

    @ApiOperation(value = "品牌馆", notes = "品牌馆")
    @GetMapping(value = "/getBrandList")
    @Export2Swagger
    public Result<List<BrandVo>> getBrandList() {
        QueryWrapper<XlProductBrand> wrapper =new QueryWrapper();
        wrapper.orderByAsc( "RAND()" ) // 随机排序（MySQL）
         . last ( "LIMIT 10" ) ; // 直接追加 SQL 片段
        //productBrandService.list();
        List<XlProductBrand> xlProductBrands = productBrandService.list(wrapper);
        List<BrandVo> brandVos = new ArrayList<>();
        for(XlProductBrand brandTemp :xlProductBrands){
            if(ObjectUtil.isEmpty(brandTemp.getBrandLogo())){
                BrandVo bm = new BrandVo(brandTemp.getBrandName(), baseUrl+"/temp/nophoto.png");
                brandVos.add(bm);
            }else{
                BrandVo bm = new BrandVo(brandTemp.getBrandName(), baseUrl+brandTemp.getBrandLogo());
                brandVos.add(bm);
            }
        }
        return Result.OK(brandVos);
    }

    @ApiOperation(value = "热销产品", notes = "热销产品")
    @GetMapping(value = "/getHotList")
    @Export2Swagger
    public Result<List<XlProductInfo>> getHotList() {
        //先用10条数据代替
        Page<XlProductInfo> xlProductInfoIPage = new Page<>();
        xlProductInfoIPage.setSize(10);
        xlProductInfoIPage.setPages(1);

        QueryWrapper<XlProductInfo> queryWrapper = new QueryWrapper<>();

        //当前操作人
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<SysUser> sysUserWrapper = new QueryWrapper<>();
        sysUserWrapper.eq("phone",user.getPhone());
        SysUser sysUser = sysUserService.getOne(sysUserWrapper);
        if(ObjectUtil.isEmpty(sysUser)||ObjectUtil.isEmpty(sysUser.getCustomerType())){
            return Result.error("您未被授权渠道，无法查询产品");
        }
        queryWrapper.eq("type",sysUser.getCustomerType());//不存在的数据库字段，需要手动设


        List<XlProductInfo> productInfos = productInfoService.queryListByPage(xlProductInfoIPage,queryWrapper).getRecords();
        for (XlProductInfo xlProductInfoTemp : productInfos) {
            if (ObjectUtil.isNotEmpty(xlProductInfoTemp.getMainPic())) {
                xlProductInfoTemp.setMainPic(baseUrl + xlProductInfoTemp.getMainPic());
            } else {
                xlProductInfoTemp.setMainPic(baseUrl + "/temp/nophoto.png");
            }
        }
        return Result.OK(productInfos);
    }

    @ApiOperation(value = "商品列表查询", notes = "商品列表查询")
    @GetMapping(value = "/productquery")
    @Export2Swagger
    public Result<IPage<XlProductInfo>> productquery(ProductQueryRequest queryRequest,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {

        QueryWrapper<XlProductInfo> queryWrapper = new QueryWrapper<>();
        //当前操作人
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<SysUser> sysUserWrapper = new QueryWrapper<>();
        sysUserWrapper.eq("phone",user.getPhone());
        SysUser sysUser = sysUserService.getOne(sysUserWrapper);
        if(ObjectUtil.isEmpty(sysUser)||ObjectUtil.isEmpty(sysUser.getCustomerType())){
            return Result.error("您未被授权渠道，无法查询产品");
        }
        queryWrapper.eq("type",sysUser.getCustomerType());//不存在的数据库字段，需要手动设
        // @ApiModelProperty(value = "商品名称/编码/条码")
        if (ObjectUtil.isNotEmpty(queryRequest.getUpcCode())) {
            String upcCode = queryRequest.getUpcCode();
            queryWrapper.and ( wq -> wq.like ( "product_name" , upcCode ).
                    or( ).
                    like( "upc_code" , upcCode ).
                    or( ).
                    like ( "other_code" , upcCode )
            ) ;
        }


        // 分类筛选
        if (ObjectUtil.isNotEmpty(queryRequest.getCategoryId())) {
            queryWrapper.and(wq->wq.eq("l2_type_code", queryRequest.getCategoryId()).or().eq("l1_type_code", queryRequest.getCategoryId())
            );
        }

        // 品牌筛选

        if (ObjectUtil.isNotEmpty(queryRequest.getBrandName())) {
            queryWrapper.eq("brand", queryRequest.getBrandName());
        }
        // 状态筛选
        if (ObjectUtil.isNotEmpty(queryRequest.getStatus())) {
            //queryWrapper.eq("status", queryRequest.getStatus());
        }

        // 标签筛选
        if (ObjectUtil.isNotEmpty(queryRequest.getTags())) {
            // queryWrapper.eq("status", queryRequest.getStatus());
        }
//        if (request.getTags() != null && !request.getTags().isEmpty()) {
//            for (String tag : request.getTags()) {
//                queryWrapper.like("tags", tag);
//            }
//        }

        // 排序
        if (ObjectUtil.isNotEmpty(queryRequest.getSortRule())) {
            String sortRule = queryRequest.getSortRule();
            if ("default".equals(sortRule)) {//
                queryWrapper.orderByDesc("upc_code");//默认 按照upc_code 降序
            }
            if ("create_time".equals(sortRule)) {//
                queryWrapper.orderByDesc("create_time");//最新 按照create_time 降序
            }
            if ("priceasc".equals(sortRule)) {//
                queryWrapper.orderByAsc("supply_price");//最新 按照 price asc
            }
            if ("pricedesc".equals(sortRule)) {//
                queryWrapper.orderByDesc("supply_price");//最新 按照 price desc
            }
        }

        Page<XlProductInfo> page = new Page<XlProductInfo>(pageNo, pageSize);

        IPage<XlProductInfo>  productInfoIPage = productInfoService.queryListByPage(page,queryWrapper);

        for (XlProductInfo xlProductInfoTemp : productInfoIPage.getRecords()) {
            if (ObjectUtil.isNotEmpty(xlProductInfoTemp.getMainPic())) {
                xlProductInfoTemp.setMainPic(baseUrl + xlProductInfoTemp.getMainPic());
            } else {
                xlProductInfoTemp.setMainPic(baseUrl + "/temp/nophoto.png");
            }
        }
        return Result.OK(productInfoIPage);
    }

    @ApiOperation(value = "获取查询条件", notes = "获取查询条件")
    @GetMapping(value = "/getQueryCondition")
    @Export2Swagger
    public Result<QueryConditionResponse> getQueryCondition() {
        QueryConditionResponse queryConditionResponse = new QueryConditionResponse();

        // 查询分类列表
        //List<XlProductType> categories = productTypeService.list(new QueryWrapper<XlProductType>().eq("has_child", "0"));

        queryConditionResponse.setCategories( productTypeService.queryProductTypeAsTree()) ;

        // 查询品牌列表
        List<XlProductBrand> brands = productBrandService.getAllBrand();
        for(XlProductBrand brantemp: brands){
            if(ObjectUtil.isEmpty(brantemp.getBrandLogo())){
                brantemp.setBrandLogo( baseUrl+"/temp/nophoto.png");
            }else{
                brantemp.setBrandLogo( baseUrl+brantemp.getBrandLogo());
            }

        }
        queryConditionResponse.setBrands(brands);

        // 状态列表
        List<String> statusList = Arrays.asList("有货", "买过", "收藏");
        queryConditionResponse.setStatusList(statusList);

        // 标签列表
        List<String> tags = Arrays.asList("新品", "热销", "清仓", "爆款", "推荐");
        queryConditionResponse.setTags(tags);

        // 排序规则列表
        List<SortRule> sortRules = Arrays.asList(
                new SortRule("upc_code", "默认"),
                new SortRule("create_time", "最新"),
                new SortRule("priceasc", "价格从低到高"),
                new SortRule("pricedesc", "价格从高到低")
        );
        queryConditionResponse.setSortRules(sortRules);

        return Result.OK(queryConditionResponse);
    }

    @Resource
    private IXlCustomerMystoreService xlCustomerMystoreService;

    @Autowired
    private IXlCustomerStoreInfoService xlCustomerStoreInfoService;

    @ApiOperation(value = "用户登录", notes = "用户登录")
    @PostMapping(value = "/mplogin")
    @Export2Swagger
    @IgnoreAuth
    public Result<JSONObject> mplogin(@RequestBody MPLoginModel mpLoginModel, HttpServletRequest request) {
        Result<JSONObject> result = new Result<JSONObject>();

        //登录方式1：使用账密登录 登录成功后在判断身份
        //先试用 账号或者openid 找到用户
        List<SysUser> sysUsers = sysUserService.getUserByNameAndPhoneAndOpenid(mpLoginModel.getUsername(),null,null);

        if (ObjectUtil.isEmpty(sysUsers)) {
            result.error500("用户不存在，请先注册！");
            return result;
        }

        SysUser sysUser  = sysUsers.get(0);;

        String userpassword = PasswordUtil.encrypt(mpLoginModel.getUsername(), mpLoginModel.getPassword(), sysUser.getSalt());
        String syspassword = sysUser.getPassword();
        if (!syspassword.equals(userpassword)) {
            result.error500("用户名或密码错误");
            return result;
        }

        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setUsername(sysUser.getUsername());
        userInfoVO.setAvatar(sysUser.getAvatar());
        userInfoVO.setCustomerType(sysUser.getCustomerType());
        if(mpLoginModel.getIsDriver()){//司机端
            if("1".equals(sysUser.getIsDrive())){
                userInfoVO.setIsDriver(true);
            }else{
                return result.error500("你没有司机权限，请联系管理员！！");
            }

        }else{//门店端
            if(ObjectUtil.isEmpty(sysUser.getCustomerType())){
                return result.error500("该用户未授权渠道，无法登录，请联系管理员！！");
            }
            //查询门店
            List<MyStoreVO> myStoreList = getMystoreVOList(sysUser.getPhone());
            if(ObjectUtil.isEmpty(myStoreList)){
                userInfoVO.setIsCheck(false);
                return result.error500("该用户未被设置所辖门店，无法登录，请联系管理员！！");
            }else{
                userInfoVO.setIsCheck(true);
                userInfoVO.setChargeStore(myStoreList);
            }
        }

        //6. 生成token
        String token = JwtUtil.sign(sysUser.getUsername(), sysUser.getPassword());
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        // 获取用户部门信息
        JSONObject obj = new JSONObject(new LinkedHashMap<>());
        //token 信息
        obj.put("userinfo", userInfoVO);
        //token 信息
        obj.put("token", token);
        result.setResult(obj);
        result.setSuccess(true);
        result.setCode(200);

        return result;
    }

    @ApiOperation(value = "用户注册", notes = "用户注册")
    @PostMapping(value = "/mpregister")
    @Export2Swagger
    @IgnoreAuth
    public Result<JSONObject> userRegister(@RequestBody MPRegisterModel registerModel) {
        Result<JSONObject> result = new Result<JSONObject>();
        String phone = registerModel.getPhone();
        String username = registerModel.getUsername();
        String password = registerModel.getPassword();
        String openid = registerModel.getOpenid();
        //未设置用户名，则用手机号作为用户名
        if (oConvertUtils.isEmpty(username)) {
            username = phone;
        }
        //允许一个openid注册多个用户
        List<SysUser> sysUsers = sysUserService.getUserByNameAndPhoneAndOpenid(username,phone,null);

        if (ObjectUtil.isAllNotEmpty(sysUsers)) {
            result.setMessage("用户名或phone已注册,请核实");
            result.setSuccess(false);
            return result;
        }

        try {
            SysUser user = new SysUser();
            user.setCreateTime(new Date());// 设置创建时间
            String salt = RandomUtil.randomString(8);
            if(ObjectUtil.isEmpty(password)){
                password = "qq123123";
            }
            String passwordEncode = PasswordUtil.encrypt(username, password, salt);
            user.setSalt(salt);
            user.setUsername(username);
            user.setRealname(username);
            user.setPassword(passwordEncode);
            user.setAvatar(baseUrl + "brand/a1.jpg");
            user.setBirthday(new Date());
            user.setSex(1);
            user.setEmail( RandomUtil.randomString(8)+"@htm.com");
            user.setPhone(phone);
            user.setStatus(3);//注册用户未审核
            user.setThirdType("weixinmp");
            user.setThirdId(openid);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            user.setConfirmFlag(CommonConstant.DEL_FLAG_0);
            user.setActivitiSync(CommonConstant.ACT_SYNC_1);
            user.setCreateBy("admin");
            user.setLoginTenantId(1001);
            sysUserService.addUserWithRole(user, "");//默认临时角色 test
            result.success("注册成功，请联系管理人员审核后，方可登录");
        } catch (Exception e) {
            result.error500("注册失败");
        }
        return result;
    }

    @ApiOperation(value = "获取我的信息", notes = "获取我的信息")
    @GetMapping(value = "/getpersoninfo")
    @Export2Swagger
    public Result<UserInfoVO> getmyinfo(HttpServletRequest request) {
        Result<UserInfoVO> result = new Result<UserInfoVO>();
        //当前操作人
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(ObjectUtil.isEmpty(user)){
            return result.error500("登录异常！！");
        }

        // 根据用户名查询用户信息
        UserInfoVO userInfoVO = new UserInfoVO();
        SysUser sysUser = sysUserService.getUserByName(user.getUsername());
        userInfoVO.setUsername(user.getUsername());
        userInfoVO.setAvatar(user.getAvatar());
        userInfoVO.setCustomerType(sysUser.getCustomerType());
        if("1".equals(sysUser.getIsDrive())){
            userInfoVO.setIsDriver(true);
        }else{
            List<MyStoreVO> myStoreList = getMystoreVOList(user.getPhone());
            if(ObjectUtil.isEmpty(myStoreList)){
                return result.error500("该用户未被设置所属门店，无法登陆，请联系管理员！！");
            }
            userInfoVO.setChargeStore(myStoreList);
        }
        result.setResult(userInfoVO);
        return result;

    }
    @Resource
    private IXlCustomerOrdeService xlCustomerOrdeService;
    @Resource
    private IXlCustomerAsService asService;
    @ApiOperation(value = "获取门店的未付金额", notes = "获取门店的未付金额")
    @GetMapping(value = "/getStoreUnpayAmount")
    @Export2Swagger
    public Result<MyStoreVO> getStoreUnpayAmount(@RequestParam(name = "storeCode") String storeCode) {
        Result<MyStoreVO> result = new Result<MyStoreVO>();
        MyStoreVO myStoreVO  = xlCustomerOrdeService.getStoreUnpayAmount(storeCode);
        //获取角标数据
        List<Map> cornerNumMap = xlCustomerOrdeService.getCornerNum(storeCode);
        if(ObjectUtil.isNotEmpty(cornerNumMap)){
            for(Map corner : cornerNumMap){
                if("待提交".equals(corner.get("order_status"))){
                    myStoreVO.setNotCommitCornerData(Integer.valueOf(corner.get("status_corner").toString()));
                } else if("待支付".equals(corner.get("order_status"))){
                    myStoreVO.setNotPayCornerData(Integer.valueOf(corner.get("status_corner").toString()));
                }else if("待审核".equals(corner.get("order_status"))){
                    myStoreVO.setNotAuditCornerData(Integer.valueOf(corner.get("status_corner").toString()));
                }else if("待发货".equals(corner.get("order_status"))){
                    myStoreVO.setNotShipCornerData(Integer.valueOf(corner.get("status_corner").toString()));
                }else if("待收货".equals(corner.get("order_status"))){
                    myStoreVO.setNotRevievrCornerData(Integer.valueOf(corner.get("status_corner").toString()));
                }
            }
        }
        //获取门店的进行中的售后单，包括 待审核，退款中
        IPage<XlCustomerAs> xlCustomerAsIPage = asService.getASListByPage("待处理",null,storeCode,1,100);
        if(ObjectUtil.isNotEmpty(xlCustomerAsIPage)){
            myStoreVO.setSHCornerData(xlCustomerAsIPage.getRecords().size());
        }
        result.setResult(myStoreVO);
        return result;
    }
    @ApiOperation(value = "jscode2session", notes = "jscode2session")
    @GetMapping(value = "/jscode2session")
    @Export2Swagger
    @IgnoreAuth
    public Result<JSONObject> jscode2session(  @RequestParam(value = "js_code") String js_code ){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx45e42864bc3f30eb&secret=fc6660310c197f1a97473f506c70786d&js_code="+js_code+"&grant_type=authorization_code" ;
        String resultJson = HttpUtil.get(url);
        //System.out.println("返回结果数据：" + JSON.toJSONString(result));
        JSONObject jsonObject = JSON.parseObject(resultJson);
        return Result.OK(jsonObject);
    }
    @GetMapping(value = "/logout")
    @Export2Swagger
    @ApiOperation(value = "退出登录", notes = "退出登录")
    public Result<Object> logout(HttpServletRequest request, HttpServletResponse response) {
        //用户退出逻辑
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if(ObjectUtil.isEmpty(token)) {
            return Result.error("退出登录失败！");
        }
        //清空用户登录Token缓存
        redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
        //调用shiro的logout
        SecurityUtils.getSubject().logout();
        return Result.ok("退出登录成功！");
    }

    private List<MyStoreVO> getMystoreVOList (String phone){
        //查询门店
        List<MyStoreVO> myStoreVOList = new ArrayList<>();
        QueryWrapper<XlCustomerMystore> mystoreWrapper = new QueryWrapper<>();
        mystoreWrapper.eq("phone",phone);
        List<XlCustomerMystore> mystoreList = mystoreService.list(mystoreWrapper);
        for (XlCustomerMystore mystore1 : mystoreList){
            MyStoreVO mys = new MyStoreVO();
            mys.setStoreCode(mystore1.getStoreCode());
            mys.setStoreName(mystore1.getStoreName());
            myStoreVOList.add(mys);
        }
        return myStoreVOList;
    }

    @GetMapping(value = "/getDict/{dictCode}")
    @Export2Swagger
    @ApiOperation(value = "获取业务字典", notes = "获取业务字典")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictCode", value = "字典key", required = true, paramType = "query", dataType = "String",allowableValues="asType,applyReason",allowMultiple=false),
    })
    public Result<List<DictModel>> getDict(@PathVariable("dictCode") String dictCode) {
       if("asType".equals(dictCode)){//售后单类型
            return Result.ok(Arrays.asList(
                    new DictModel("仅退款-整单退","仅退款-整单退"),
                    new DictModel("仅退款-部分退","仅退款-部分退"),
                    new DictModel("退货退款-整单退","退货退款-整单退"),
                    new DictModel("退货退款-部分退","退货退款-部分退")
            ));
       }
        if("applyReason".equals(dictCode)){//售后单类型
            return Result.ok(Arrays.asList(
                    new DictModel("缺货","缺货"),
                    new DictModel("破损/产品有污染","破损/产品有污染"),
                    new DictModel("赠品","赠品"),
                    new DictModel("其他","其他")
            ));
        }
        return Result.ok(Arrays.asList());
    }


}